#include "config.hpp"
#include "logger.hpp"
#include <fstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

Config& Config::get_instance() {
    static Config instance;    
    return instance;
}

void Config::load_config(const std::string& config_path) {
    try {
        // 读取配置文件
        std::ifstream config_file(config_path);
        if (!config_file.is_open()) {
            throw std::runtime_error("Failed to open config.json");
        }

        json config;
        config_file >> config;

        // 获取实例
        Config& instance = Config::get_instance();

        // 加载服务器配置
        instance.server_address_ = config["server"]["address"].get<std::string>();
        instance.server_port_ = config["server"]["port"].get<unsigned short>();

        // 加载MySQL配置
        instance.mysql_host_ = config["mysql"]["host"].get<std::string>();
        instance.mysql_port_ = config["mysql"]["port"].get<int>();
        instance.mysql_user_ = config["mysql"]["user"].get<std::string>();
        instance.mysql_password_ = config["mysql"]["password"].get<std::string>();
        instance.mysql_database_ = config["mysql"]["database"].get<std::string>();
        instance.mysql_pool_initial_size_ = config["mysql"]["pool"]["initial_size"].get<size_t>();
        instance.mysql_pool_max_size_ = config["mysql"]["pool"]["max_size"].get<size_t>();
        instance.mysql_pool_max_idle_time_ = config["mysql"]["pool"]["max_idle_time"].get<size_t>();
        instance.mysql_pool_connection_timeout_ = config["mysql"]["pool"]["connection_timeout"].get<size_t>();

        // 加载Redis配置
        instance.redis_host_ = config["redis"]["host"].get<std::string>();
        instance.redis_port_ = config["redis"]["port"].get<int>();
        instance.redis_pool_initial_size_ = config["redis"]["pool"]["initial_size"].get<size_t>();
        instance.redis_pool_max_size_ = config["redis"]["pool"]["max_size"].get<size_t>();
        instance.redis_pool_max_idle_time_ = config["redis"]["pool"]["max_idle_time"].get<size_t>();
        instance.redis_pool_connection_timeout_ = config["redis"]["pool"]["connection_timeout"].get<size_t>();

        Logger::info("Configuration loaded successfully");
    } catch (const std::exception& e) {
        Logger::error("Failed to load configuration: {}", e.what());
        throw;
    }
} 